package org.xx.armory.config;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.binder.DigesterLoader;
import org.junit.Before;
import org.junit.BeforeClass;
import org.xml.sax.SAXException;

import java.io.IOException;

import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;

public abstract class ConfigurationTestFixture {
    private static DigesterLoader LOADER;
    private Digester digester;

    @BeforeClass
    public static void setUpOnce()
            throws IOException, SAXException {
        ConfigurationRulesModule rulesModule = new ConfigurationRulesModule();

        LOADER = newLoader(new ConfigurationRulesModule())
                .setNamespaceAware(true)
                .setXIncludeAware(true)
                .setSchema(rulesModule.loadSchema())
                .setValidating(false);
    }

    @Before
    public void setUp() {
        this.digester = LOADER.newDigester();
    }

    /**
     * 加载指定的配置文件。
     *
     * @param fileName
     *         配置文件名，相对于当前类的路径。
     * @return 已加载的配置项。
     * @throws IOException
     *         如果指定的配置文件无法访问，或者解析指定的配置文件出错。
     */
    protected final Configuration parse(
            String fileName
    )
            throws IOException {
        try {
            return this.digester.parse(getClass().getResourceAsStream(fileName));
        } catch (SAXException ex) {
            throw new IOException(ex);
        }
    }
}
